package com.moli.iov.base.remote.impl;

import com.moli.iov.base.constants.DictConstants;
import com.moli.iov.base.enums.SysParamSettingEnum;
import com.moli.iov.base.model.dto.DictDataQueryByTypeDto;
import com.moli.iov.base.model.dto.SysParamSettingsCacheBean;
import com.moli.iov.base.model.dto.req.SysParamSettingsQueryReqDto;
import com.moli.iov.base.model.dto.req.SysParamSettingsReqDto;
import com.moli.iov.base.model.dto.res.SysParamSettingsResDto;
import com.moli.iov.base.model.po.DictData;
import com.moli.iov.base.model.po.SysParamSettings;
import com.moli.iov.base.model.po.VehicleTbox;
import com.moli.iov.base.remote.ISysParamSettingsRemoteService;
import com.moli.iov.base.service.IDictDataService;
import com.moli.iov.base.service.ISysParamSettingsService;
import com.moli.iov.base.service.IVehicleTboxService;
import com.moli.iov.base.util.CollectionUtils;
import com.moli.iov.model.dto.req.PageExtend;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.JsonUtils;
import com.moli.iov.util.ValidationUtils;

import java.util.*;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * The type Sys param settings remote service.
 *
 * @author wanghualin
 * @date 2019 -10-08 19:44:10
 */
@Service(group = "${service.group}")
@Slf4j
public class ISysParamSettingsRemoteServiceImpl implements ISysParamSettingsRemoteService {

    @Autowired
    private ISysParamSettingsService settingsService;

    @Autowired
    private IDictDataService iDictDataService;
    @Autowired
    private IVehicleTboxService iVehicleTboxService;

    @Override
    public RestResponse initSysParamSettings(SysParamSettingsReqDto userDto) {
        log.info("初始化系统设置入参SysParamSettingsReqDto:{}" + userDto);
        ValidationUtils.validateBean(userDto, SysParamSettingsReqDto.Save.class);

        List<SysParamSettings> sysParamSettingsByCompanyId = settingsService
                .getSysParamSettingsByCompanyId(userDto.getCompanyId());
        if (!CollectionUtils.isEmpty(sysParamSettingsByCompanyId)) {
            return RestResponse.failure("已存在");
        }    //组装
        List<SysParamSettings> settingsList = assemblySysParamSettings(userDto);
        if (!CollectionUtils.isEmpty(settingsList)) {
            settingsService.saveBatchSysParamSettings(settingsList, userDto.getCompanyId());
            return RestResponse.success();
        }
        return RestResponse.failure("保存失败");
    }

    private List<SysParamSettings> assemblySysParamSettings(SysParamSettingsReqDto userDto) {

        DictDataQueryByTypeDto dictDataQueryByTypeDto = new DictDataQueryByTypeDto();
        dictDataQueryByTypeDto.setDictType(DictConstants.SYS_PARAMETER);
        RestResponse<List<DictData>> dict = iDictDataService
                .queryListByType(dictDataQueryByTypeDto);
        List<SysParamSettings> settingsList = new ArrayList<>();
        if (dict.isFlag() && !CollectionUtils.isEmpty(dict.getData())) {
            for (DictData datum : dict.getData()) {
                SysParamSettings settings = new SysParamSettings();
                settings.setParamCode(datum.getDictCode());
                settings.setParamDesc(datum.getRemark());
                settings.setParamName(datum.getDictValue());
                SysParamSettingEnum sys = SysParamSettingEnum
                        .getSysParamSettingEnumByDictCode(datum.getDictCode());
                ValidationUtils.validateBean(sys);
                settings.setParamUnit(sys.getUnit());
                settings.setParamValue(sys.getDefaultsValue());
                settings.setCompanyId(userDto.getCompanyId());
                settings.setCompanyName(userDto.getCompanyName());
                Date time = Calendar.getInstance().getTime();
                settings.setCreateUser(userDto.getSysAccount());
                settings.setCreateUserId(userDto.getSysUserId());
                settings.setModifiedUserId(userDto.getSysUserId());
                settings.setGmtCreate(time);
                settings.setGmtModified(time);
                settings.setModifiedUser(userDto.getSysAccount());
                settingsList.add(settings);
            }
        }
        return settingsList;
    }

    @Override
    public RestResponse updateSysParamSettings(SysParamSettingsReqDto dto) {
        log.info("系统设置-系统设置参数-修改-入参SysParamSettingsReqDto:{}", JsonUtils.toJson(dto));
        ValidationUtils.validateBean(dto, SysParamSettingsReqDto.Update.class);
        SysParamSettings byId = settingsService.getSysParamSettingsById(dto.getId());
        ValidationUtils.validateBean(byId);
        CommonUtils.copyProperties(dto, byId);
        byId.setGmtModified(new Date());
        byId.setModifiedUser(dto.getSysAccount());
        byId.setModifiedUserId(dto.getSysUserId());
        settingsService.updateSysParamSettings(byId);
        RestResponse success = RestResponse.success();
        log.info("系统设置-系统设置参数-修改-出参RestResponse:{}", JsonUtils.toJson(success));
        return success;
    }

    @Override
    public PageExtend<SysParamSettingsResDto> listSysParamSettings(SysParamSettingsQueryReqDto reqDto) {
        log.info("系统设置-系统设置参数-列表-入参SysParamSettingsReqDto:{}", JsonUtils.toJson(reqDto));
        PageExtend<SysParamSettingsResDto> sysParamSettingsResDtoPageExtend = settingsService.listSysParamSettings(reqDto);
        log.info("系统设置-系统设置参数-列表-出参PageExtend<SysParamSettingsResDto>:{}", JsonUtils.toJson(sysParamSettingsResDtoPageExtend));
        return sysParamSettingsResDtoPageExtend;
    }

    @Override
    public RestResponse<Map<String, SysParamSettingsCacheBean>> getSysParamSettingsCacheBeanByVin(
            List<String> vinList) {
        List<VehicleTbox> list = iVehicleTboxService.listVehicleTboxList(vinList);
        if (CollectionUtils.isEmpty(list)) {
            return RestResponse.failure("车辆不存在");
        }
        Map<Long, List<String>> collect = list.stream().filter(vehicleTbox ->
                vehicleTbox.getCompanyId() != null && vehicleTbox.getCompanyId().longValue() != 0)
                .collect(Collectors
                        .groupingBy(VehicleTbox::getCompanyId,
                                Collectors.mapping(VehicleTbox::getVin, Collectors.toList())));
        if (CollectionUtils.isEmpty(collect)) {
            return RestResponse.failure("车辆没有所属公司");
        }
        Map<String, String> jsonStr = settingsService.listSysParamSettingsCacheBean();
        if (CollectionUtils.isEmpty(jsonStr)) {
            return RestResponse.failure("系统设置不存在");
        }
        Map<String, SysParamSettingsCacheBean> map = new HashMap<>();
        collect.forEach((aLong, strings) -> {
            String str = jsonStr.get(aLong.toString());
            if (StringUtils.isNotBlank(str)) {
                SysParamSettingsCacheBean parse = JsonUtils
                        .parse(str, SysParamSettingsCacheBean.class);
                strings.forEach(s -> map.put(s, parse));
            }
        });
        return RestResponse.success(map);
    }

    @Override
    public RestResponse<List<SysParamSettingsResDto>> listSysParamSettingsOp(Long companyId) {
        List<SysParamSettings> sys = settingsService.getSysParamSettingsByCompanyId(companyId);
        return RestResponse.success(toSysParamSettingsReqDtoList(sys));
    }

    private List<SysParamSettingsResDto> toSysParamSettingsReqDtoList(List<SysParamSettings> sysParamSettingsList) {
        if (CollectionUtils.isEmpty(sysParamSettingsList)) {
            return Collections.emptyList();
        }
        List<SysParamSettingsResDto> sys = new ArrayList<>();
        for (SysParamSettings sysParamSettings : sysParamSettingsList) {
            SysParamSettingsResDto dto = new SysParamSettingsResDto();
            CommonUtils.copyProperties(sysParamSettings, dto);
            sys.add(dto);
        }
        return sys;
    }

}
